﻿using RepositoryFramework.Exceptions;
using RepositoryFramework.Validators;
using FluentValidation;
using FluentValidation.Results;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Portal.Logic.Validators;
using Portal.Model;
using Portal.Repository;
using Rhino.Mocks;

namespace Portal.Logic.Services.Tests.Units
{
	[TestClass()]
	public class UserServiceTests : ServiceBaseTests<UserService, IUser, IUserValidator, IPortalUnitOfWorkProvider, IPortalUnitOfWork>
	{
		private IUserRepository _repository;

		protected override void InitializeTest()
		{
			base.InitializeTest();

			_repository = Mocks.DynamicMock<IUserRepository>();
			Validator = Mocks.DynamicMock<IUserValidator>();
			SetupResult.For(UnitOfWork.UserRepository).Return(_repository);
		}

		#region AddOrUpdate

		[TestMethod()]
		public void AddOrUpdate_EntityIsValid_Processed()
		{
			var entity = Mocks.DynamicMock<IUser>();
			SetupResult.For(entity.Login).Return("login");
			var validationResult = Mocks.DynamicMock<IValidationResult>();
			SetupResult.For(validationResult.IsValid).Return(true);
			Expect.Call(Validator.Validate(entity)).IgnoreArguments().Return(validationResult);
			Expect.Call(_repository.AddOrUpdate(entity)).Return(entity);
			Mocks.ReplayAll();

			var service = GetService();
			var result = service.AddOrUpdate(entity);

			Assert.AreEqual(entity, result);
		}

		[TestMethod()]
		[ExpectedException(typeof(CustomValidationException))]
		public void AddOrUpdate_EntityIsNotValid_ThrowException()
		{
			var entity = Mocks.DynamicMock<IUser>();
			var validationResult = Mocks.DynamicMock<IValidationResult>();
			SetupResult.For(validationResult.IsValid).Return(false);
			Expect.Call(Validator.Validate(entity)).IgnoreArguments().Return(validationResult);
			Expect.Call(_repository.AddOrUpdate(entity)).Return(entity);
			Mocks.ReplayAll();

			var service = GetService();
			var result = service.AddOrUpdate(entity);

			Assert.AreEqual(entity, result);
		}

		#endregion AddOrUpdate

		protected override UserService GetService()
		{
			return new UserService(Provider, Validator);
		}
	}
}